package edu.hwadee.BEIS.serviceImpl;

import java.util.Calendar;
import java.util.Set;

import edu.hwadee.BEIS.dto.GlobalCooperationDTO;
import edu.hwadee.BEIS.dto.MajorGradeCourseConstructionDTO;
import edu.hwadee.BEIS.dto.SchoolConditionDTO;
import edu.hwadee.BEIS.entity.*;
import edu.hwadee.BEIS.util.FileUtil;
import edu.hwadee.BEIS.service.SchoolUserService;
import edu.hwadee.BEIS.util.FileUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import edu.hwadee.BEIS.constants.CustomException;
import edu.hwadee.BEIS.constants.ResultEnum;
import edu.hwadee.BEIS.service.SchoolUserService;
import org.springframework.web.multipart.MultipartFile;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Set;

import static edu.hwadee.BEIS.util.FileUtil.parseXML;

/**
 * 学校用户Service实现类
 * @author kingsong
 *
 */
@Service
@Transactional
public class SchoolUserServiceImpl extends BaseService implements SchoolUserService {

    @Override
    public SchoolBasicInfor getSchoolBasicInfor(String schoolUser_id) throws Exception {
        if (schoolUserRepo.exists(schoolUser_id)) {
            return schoolUserRepo.findOne(schoolUser_id).getSchoolBasic();
        } else {
            throw new CustomException(ResultEnum.SCHOOL_USER_NOTEXIST);
        }

    }

    @Override
    public Set<StudentBasicSituation> getStudentBasicSituationForOneYear(String schoolUser_id) throws Exception {
        if (schoolUserRepo.exists(schoolUser_id)) {
            SchoolBasicInfor schoolBasicInfor = schoolUserRepo.findOne(schoolUser_id).getSchoolBasic();
            Calendar now = Calendar.getInstance();
            now.setTime(new Date());
            now.add(Calendar.YEAR, -1);
            Date from = now.getTime();
            Set<StudentBasicSituation> sbs = studentBasicSituationRepo.findBySchoolBasicIsAndCountyAuditStatusIsAndCityAuditStatusIsAndModifyTimeAfterOrderByModifyTime(schoolBasicInfor, (short) 1, (short) 1, from);
            return sbs;
        } else {
            throw new CustomException(ResultEnum.SCHOOL_USER_NOTEXIST);
        }
    }

    @Override
    public Set<WholeSchoolTrainingBase> getWholeSchoolTrainingBaseForOneYear(String schoolUser_id) throws Exception {
        if (schoolUserRepo.exists(schoolUser_id)) {
            SchoolBasicInfor schoolBasicInfor = schoolUserRepo.findOne(schoolUser_id).getSchoolBasic();
            Calendar now = Calendar.getInstance();
            now.setTime(new Date());
            now.add(Calendar.YEAR, -1);
            Date from = now.getTime();
            Set<WholeSchoolTrainingBase> wstb = wholeSchoolTrainingBaseRepo.findBySchoolBasicIsAndCountyAuditStatusIsAndCityAuditStatusIsAndModifyTimeAfterOrderByModifyTime(schoolBasicInfor, (short) 1, (short) 1, from);
            return wstb;
        } else {
            throw new CustomException(ResultEnum.SCHOOL_USER_NOTEXIST);
        }
    }

    @Override
    public PublicTrainingBase getNewestPublicTrainingBase(String schoolUser_id) throws Exception {
        if (schoolUserRepo.exists(schoolUser_id)) {
            SchoolBasicInfor schoolBasicInfor = schoolUserRepo.findOne(schoolUser_id).getSchoolBasic();
            Calendar now = Calendar.getInstance();
            now.setTime(new Date());
            now.add(Calendar.YEAR, -1);
            Date from = now.getTime();
            PublicTrainingBase ptb = publicTrainingBaseRepo.findFirstBySchoolBasicIsAndCountyAuditStatusIsAndCityAuditStatusIsOrderByModifyTimeDesc(schoolBasicInfor, (short) 1, (short) 1);
            return ptb;
        } else {
            throw new CustomException(ResultEnum.SCHOOL_USER_NOTEXIST);
        }
    }

    @Override
    public SchoolCondition getSchoolCondition(String schoolUser_id) throws Exception {
        if (schoolUserRepo.exists(schoolUser_id)) {
            return schoolConditionRepo.findOneBySchoolBasicIsAndCountyAuditStatusIsAndCityAuditStatusIsOrderByModifyTimeDesc(schoolUserRepo.findOne(schoolUser_id).getSchoolBasic(), (short) 1, (short) 1);
        } else {
            throw new CustomException(ResultEnum.SCHOOL_USER_NOTEXIST);
        }
    }

    /**
     * 添加国际合作信息
     *
     * @param globalCooperation
     * @return
     */
    public boolean addGlobalCooperation(GlobalCooperation globalCooperation) {
        globalCooperationRepo.save(globalCooperation);
        return true;
    }

    /**
     * 封装信息
     *
     * @param globalCooperationDTO
     * @return
     */
    public GlobalCooperation globalCooperation2object(GlobalCooperationDTO globalCooperationDTO) throws Exception {
        if (globalCooperationRepo.exists(globalCooperationDTO.getGlobalCooperationId())) {
            //学校不存在
            throw new CustomException(ResultEnum.SCHOOL_NOT_EXIST);

        }
        GlobalCooperation globalCooperation = new GlobalCooperation();
        BeanUtils.copyProperties(globalCooperationDTO, globalCooperation);
        return globalCooperation;
    }

    /**
     * 添加学校基本信息
     */
    @Override
    public boolean addSchoolBasicInfor(SchoolBasicInfor schoolBasicInfor) {
        schoolBasicInforRepo.save(schoolBasicInfor);
        return true;
    }

    public void updateSchoolBasicInfor(SchoolBasicInfor sbi, String user_id) throws CustomException{
        sbi.setSchoolId(schoolUserRepo.findOneBySchoolUserId(user_id).getSchoolBasic().getSchoolId());
        if(!isOpenModify(2,user_id, new Date())){
            throw new CustomException(ResultEnum.NOT_REGISTER_TIME);
        } else {
            schoolBasicInforRepo.save(sbi);
        }
    }
    /**
     * 添加学校办学条件
     */
    @Override
    public boolean addSchoolCondition(SchoolConditionDTO schoolConditionDTO, SchoolBasicInfor schoolBasicInfor) {
        if (schoolBasicInfor == null) {
            // 学校不存在
            throw new CustomException(ResultEnum.SCHOOL_NOT_EXIST);
        } else {
            SchoolCondition schoolCondition = new SchoolCondition();
            BeanUtils.copyProperties(schoolConditionDTO, schoolCondition);
            schoolCondition.setSchoolBasic(schoolBasicInfor);
            schoolCondition.setCityAuditStatus((short) 0);
            schoolCondition.setCountyAuditStatus((short) 0);
            schoolCondition.setModifyTime(new Date());
            schoolCondition = schoolConditionRepo.save(schoolCondition);//获取Id
            //保存文件
            MultipartFile localAverageBudgetaryAppropriationFile = schoolConditionDTO.getLocalAverageBudgetaryAppropriationFile();
            MultipartFile localFinancialSpecialAllocationFile = schoolConditionDTO.getLocalFinancialSpecialAllocationFile();
            String localAverageBudgetaryAppropriationFilePath = FileUtil.saveFile("schoolCondition", localAverageBudgetaryAppropriationFile, schoolCondition.getConditionId() + "_" + localAverageBudgetaryAppropriationFile.getOriginalFilename());
            String localFinancialSpecialAllocationFilePath = FileUtil.saveFile("schoolCondition", localFinancialSpecialAllocationFile, schoolCondition.getConditionId() + "_" + localFinancialSpecialAllocationFile.getOriginalFilename());
            schoolCondition.setLocalAverageBudgetaryAppropriation(localAverageBudgetaryAppropriationFilePath);
            schoolCondition.setLocalFinancialSpecialAllocation(localFinancialSpecialAllocationFilePath);
            schoolConditionRepo.save(schoolCondition);
            return true;
        }
    }

    /**
     * 添加专业年级课程建设管理
     *
     * @param majorGradeCourseConstructionFile
     * @return
     */
    public boolean addMajorGradeCourseConstruction(MultipartFile majorGradeCourseConstructionFile,SchoolBasicInfor schoolBasicInfor) {
        if (schoolBasicInfor == null) {
            // 学校不存在
            throw new CustomException(ResultEnum.SCHOOL_NOT_EXIST);
        } else {
            MajorGradeCourseConstruction majorGradeCourseConstruction = new MajorGradeCourseConstruction();
            //封装信息
            majorGradeCourseConstruction.setSchoolBasic(schoolBasicInfor);
            majorGradeCourseConstruction.setCityAuditStatus((short) 0);
            majorGradeCourseConstruction.setCountyAuditStatus((short) 0);
            majorGradeCourseConstruction.setModifyTime(new Date());

            //解析文件



            majorGradeCourseConstructionRepo.save(majorGradeCourseConstruction);
            return true;
        }
    }

    /**
     * 添加校企合作信息
     * @param schoolCompanyCooperationFile
     * @param schoolBasicInfor
     * @return
     */
    public boolean addSchoolCompanyCooperation(MultipartFile schoolCompanyCooperationFile,SchoolBasicInfor schoolBasicInfor) {
        if (schoolBasicInfor == null) {
            // 学校不存在
            throw new CustomException(ResultEnum.SCHOOL_NOT_EXIST);
        } else {
            SchoolCompanyCooperation schoolCompanyCooperation = new SchoolCompanyCooperation();
            //封装信息
            schoolCompanyCooperation.setSchoolBasic(schoolBasicInfor);
            schoolCompanyCooperation.setCityAuditStatus((short) 0);
            schoolCompanyCooperation.setCountyAuditStatus((short) 0);
            schoolCompanyCooperation.setModifyTime(new Date());

            //解析文件



            schoolCompanyCooperationRepo.save(schoolCompanyCooperation);
            return true;
        }
    }

    /**
     * 添加参与职教集团情况
     * @param vocationalEducationalGroupFile
     * @param schoolBasicInfor
     * @return
     */
    public boolean addVocationalEducationalGroup(MultipartFile vocationalEducationalGroupFile,SchoolBasicInfor schoolBasicInfor) {
        if (schoolBasicInfor == null) {
            // 学校不存在
            throw new CustomException(ResultEnum.SCHOOL_NOT_EXIST);
        } else {
            VocationalEducationalGroup vocationalEducationalGroup = new VocationalEducationalGroup();
            //封装信息
            vocationalEducationalGroup.setSchoolBasic(schoolBasicInfor);
            vocationalEducationalGroup.setCityAuditStatus((short) 0);
            vocationalEducationalGroup.setCountyAuditStatus((short) 0);
            vocationalEducationalGroup.setModifyTime(new Date());

            //解析文件



            vocationalEducationalGroupRepo.save(vocationalEducationalGroup);
            return true;
        }
    }

    /**
     * 添加国际合作信息
     *
     * @param globalCooperationFile
     * @return
     */
    public boolean addGlobalCooperation(MultipartFile globalCooperationFile,SchoolBasicInfor schoolBasicInfor) {
        if (schoolBasicInfor == null) {
            // 学校不存在
            throw new CustomException(ResultEnum.SCHOOL_NOT_EXIST);
        } else {
            GlobalCooperation globalCooperation = new GlobalCooperation();
            //封装信息
            globalCooperation.setSchoolBasic(schoolBasicInfor);
            globalCooperation.setCityAuditStatus((short) 0);
            globalCooperation.setCountyAuditStatus((short) 0);
            globalCooperation.setModifyTime(new Date());

            //解析文件



            globalCooperationRepo.save(globalCooperation);
            return true;
        }
    }

    /**
     * 根据用户ID查找学校基本信息
     *
     * @param userId
     * @return
     * @throws Exception
     */
    public SchoolBasicInfor findSchoolBasicInfor(String userId) throws Exception {
        SchoolUser schoolUser = schoolUserRepo.findOneBySchoolUserId(userId);
        SchoolBasicInfor schoolBasicInfor = schoolUser.getSchoolBasic();
        return schoolBasicInfor;
    }

    @Async
    @Override
    public void saveMajorGradeCourseConstruction(MultipartFile multipartFile, SchoolBasicInfor schoolBasicInfor) {
        String filePath = FileUtil.saveFile("mgcc", multipartFile, multipartFile.getOriginalFilename());
        List<String> res = FileUtil.parseXML(filePath);
        MajorGradeCourseConstruction mgcc = new MajorGradeCourseConstruction();
        mgcc.setMajorCategoriesCount(Integer.valueOf(res.get(0)));
        mgcc.setMajorCategoriesNameList(res.get(1));
        mgcc.setMajorCount(Integer.valueOf(res.get(2)));
        mgcc.setMajorNameList(res.get(3));
        mgcc.setMajorDirectionCount(Integer.valueOf(res.get(4)));
        mgcc.setMajorDirectionNameList(res.get(5));
        mgcc.setCountyAuditStatus((short)0);
        mgcc.setCityAuditStatus((short)0);
        mgcc.setModifyTime(new Date());
        mgcc.setSchoolBasic(schoolBasicInfor);
        majorGradeCourseConstructionRepo.save(mgcc);

    }


    /**
     * 判断是否市属学校
     * @param sbi
     * @return
     */
    private short isCityDirect(SchoolBasicInfor sbi){
        if (cityUserRepo.findDistinctByAdminCode(sbi.getBelongId()) == null)
            return 0;
        else
            return 1;
    }

    /**
     * 通过Userid查找学校基本信息
     * @param user_id
     * @return
     */
    private SchoolBasicInfor getSchoolInfoByUserID(String user_id) {
        return schoolUserRepo.findOne(user_id).getSchoolBasic();
    }

    private boolean isOpenModify(int type, String school_id, Date date){
	    SchoolUser su = schoolUserRepo.findOne(school_id);
	    OpenModify openModify = openModifyRepo.findByTypeCodeAndSchoolUsers(type, su);
	    if(openModify != null){
	    if(date.after(openModify.getStartTime()) && date.before(openModify.getEndTime()))
	        return true;
	    else
	        return false;
	    }
	    else
	        return false;
    }

    /**
     * 增加教师基础信息
     *
     * @param tbs     教师基础信息实体类
     * @param user_id 登陆用户账户
     * @throws Exception 自定义异常
     */
    @Override
    public void addTeacherBasicSituation(TeacherBasicSituation tbs, String user_id) throws Exception {
        Date date = new Date();
        if(isOpenModify(7, user_id, date)){
        try {
            SchoolBasicInfor sbi = getSchoolInfoByUserID(user_id);
            if (sbi == null)
                throw new CustomException(ResultEnum.SCHOOL_NOT_EXIST);
            tbs.setSchoolBasic(sbi);
            tbs.setModifyTime(date);//获取当前时间
            tbs.setCityAuditStatus((short)0);
            tbs.setCountyAuditStatus(isCityDirect(sbi));
            teacherBasicSituationRepository.save(tbs);
        } catch (Exception e) {
            throw e;
        }}
        else
            throw new CustomException(ResultEnum.NOT_REGISTER_TIME);
    }

    @Override
    public Page<TeacherBasicSituation> getTeacherBasicSituations(Pageable page, String user_id) throws Exception {
        SchoolBasicInfor sbi = getSchoolInfoByUserID(user_id);
        return teacherBasicSituationRepository.findBySchoolBasicOrderByModifyTimeDesc(page, sbi);
    }

    /**
     * 增加专业大类教师信息
     *
     * @param pcts
     * @throws Exception
     */
    @Override
    public void addPublicCourseTeacherSituation(PublicCourseTeacherSituation pcts, String user_id) throws Exception {

    }

	//未完成 公共课教师信息
	@Override
	public Page<PublicCourseTeacherSituation> getPublicCourseTeacherSituation(Pageable page, String user_id) throws Exception {
		SchoolBasicInfor sbi = getSchoolInfoByUserID(user_id);
		return publicCourseTeacherSituationRepo.findBySchoolBasicOrderByModifyTimeDesc(page, sbi);
	}
	//未完成 专业教师信息
	@Override
	public void addMajorTeacherSituation(MajorTeacherSituation mts, String user_id) throws Exception {

	}

	//未完成 专业教师信息
	@Override
	public Page<MajorTeacherSituation> getMajorTeacherSituation(Pageable page, String user_id) throws Exception {
		SchoolBasicInfor sbi = schoolBasicInforRepo.findOne(user_id);
		return majorTeacherSituationRepo.findBySchoolBasicOrderByModifyTimeDesc(page, sbi);
	}

    /**
     * 增加项目填报记录
     * @param pd 项目申报记录
     * @param user_id 操作用户id
     * @param file
     */
    @Override
    public void addProjectDeclare(ProjectDeclare pd, String user_id, MultipartFile file) {
        SchoolBasicInfor sbi = getSchoolInfoByUserID(user_id);
        pd.setSchoolBasic(sbi);
        pd.setModifyTime(new Date());
        pd.setCityAuditStatus((short)0);
        pd.setCountyAuditStatus(isCityDirect(sbi));
        String fileName = file.getOriginalFilename();
        fileName = FileUtil.saveFile("projectDeclare", file, fileName);
        pd.setProjectFile(fileName);
        projectDeclareRepo.save(pd);
    }
}
